<template>
  <div
      class="navbar fixed top-0 h-16 z-30 w-full justify-center transition duration-400 ease-in-out"
      :class="{'bg-base-100 bg-opacity-60 backdrop-blur': !isTop}">
    <div class="navbar-start">
      <!--      小屏打开的菜单-->
      <div class="dropdown">
        <label tabindex="0" class="btn btn-ghost lg:hidden">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h8m-8 6h16"/>
          </svg>
        </label>
        <ul tabindex="0" class="menu menu-sm dropdown-content mt-3 p-2 shadow bg-base-100 rounded-box w-52">
          <li v-for="(item, index) in menuTree" :key="index">
            <NuxtLink :to="item.link">
              <!-- 主菜单icon -->
              <Icon :name="item.icon" size="24"/>
              {{ item.name }}
            </NuxtLink>
            <ul v-if="item.children" class="p-2">
              <li v-for="(child, childIndex) in item.children" :key="childIndex">
                <NuxtLink :to="child.link">
                  <!-- 这里是子菜单icon -->
                  <Icon :name="child.icon" size="24"/>
                  {{ child.name }}
                </NuxtLink>
              </li>
            </ul>
          </li>
        </ul>
      </div>
      <a href="/" class="btn btn-ghost normal-case text-xl">Annlcc</a>
      <!--    大屏打开的菜单-->
      <div class="navbar-center hidden lg:flex font-bold">
        <ul class="menu menu-horizontal">
          <li class="ml-1" v-for="menuItem in menuTree" :key="menuItem.name">
            <!-- 主菜单 -->
            <NuxtLink v-if="!menuItem.children" :to="menuItem.link">
              <Icon :name="menuItem.icon" size="24"/>
              {{ menuItem.name }}
            </NuxtLink>
            <!-- 带有下级菜单的 -->
            <!--            <details :open="isDetailOpen" class="dropdown" v-else>
                          <summary @mouseover="handleMouseOverDetails" @mouseleave="handleMouseLeaveDetails">
                            <NuxtLink :to="menuItem.link">
                              <Icon :name="menuItem.icon" size="24"/>
                              {{ menuItem.name }}
                            </NuxtLink>
                          </summary>
                          <ul class="menu bg-base-200 w-40 rounded-box" @mouseover="handleMouseOverDetails"
                              @mouseleave="handleMouseLeaveDetails">
                            <li v-for="childItem in menuItem.children" :key="childItem.name">
                              <NuxtLink :to="childItem.link">
                                <Icon :name="childItem.icon" size="24"/>
                                {{ childItem.name }}
                              </NuxtLink>
                            </li>
                          </ul>
                        </details>-->
          </li>
        </ul>
      </div>
    </div>
    <!--    导航栏后半部分-->
    <div class="navbar-end">
      <button class="btn-ghost btn-circle btn" @click="themeStore.toggle">
        <Icon v-if="themeStore.theme.dark" size="24" name="line-md:sunny-filled-loop-to-moon-filled-loop-transition"/>
        <Icon v-else size="24" name="line-md:moon-filled-to-sunny-filled-loop-transition"/>
      </button>
      <!-- 登录按钮或个人信息 -->
      <div class="dropdown dropdown-end ml-6" v-if="userInfo">
        <div class="flex items-center">
          <label tabindex="0" class="btn btn-ghost btn-circle avatar">
            <div class="avatar online">
              <div class="w-10 rounded-full">
                <img :src="userInfo?.avatar"/>
              </div>
            </div>
          </label>
          <p>{{ userInfo?.nickName }}</p>
        </div>
        <ul tabindex="0" class="menu menu-compact dropdown-content mt-3 p-2 shadow bg-base-200 rounded-box w-52">
          <li>
            <a class="justify-between"> 个人资料 </a>
          </li>
          <li>
            <a @click="handleLogout">退出</a>
          </li>
        </ul>
      </div>
      <div class="ml-6" v-else>
        <label class="btn btn-ghost" :for="modalId">
          登 录
        </label>
      </div>
    </div>
  </div>
  <!-- 登录Modal弹窗 -->
  <div>
    <section>
      <AnnModal :modal-id="modalId">
        <!-- 登录表单 -->
        <section v-show="showLoginForm">
          <h3 class="text-lg font-bold mb-6">登录</h3>
          <div class="space-y-4">
            <div class="space-y-2">
              <label class="text-lg font-bold">邮箱</label>
              <input
                  type="text"
                  class="input input-bordered w-full"
                  placeholder="请输入邮箱"
                  v-model="blogLoginForm.email"/>
            </div>
            <div class="space-y-2" v-if="pwdLogin">
              <label class="text-lg font-bold">密码</label>
              <input
                  type="password"
                  class="input input-bordered w-full"
                  placeholder="密码不小于5位"
                  v-model="blogLoginForm.password"/>
            </div>
            <div class="space-y-2" v-else>
              <label class="text-lg font-bold">验证码</label>
              <div class="flex items-center">
                <input
                    type="text"
                    class="input input-bordered w-full"
                    placeholder="请输入验证码"
                    v-model="blogLoginForm.code"/>
                <button class="btn btn-outline w-28 ml-4" :disabled="btnDisabled"
                        @click="getCode(blogLoginForm.email,'0')">
                  {{ btnText }}
                </button>
              </div>
            </div>

            <div class="space-y-2">
              <div class="flex justify-between">
                <a class="link link-success no-underline" @click="switchToForm('forgetPwd')">忘记密码?</a>
                <a class="link link-success no-underline" @click="pwdLogin = !pwdLogin">
                  {{ pwdLogin ? "邮箱验证码登录" : "密码登录" }}</a>
              </div>

              <button class="btn btn-lg btn-primary w-full" @click="handleLogin">登 录</button>
              <div class="flex justify-between">
                <p>
                  没有账号？<a class="link link-success no-underline" @click="switchToForm('register')">注册一个</a>
                </p>
              </div>
            </div>
            <div class="divider mb-2"/>
            <div class="flex justify-center items-center">
              <Icon
                  name="simple-icons:gitee"
                  color="#c71d23"
                  size="28"
                  class="ml-2 cursor-pointer"
                  @click="handleSocialLogin('gitee')"
              />
            </div>
          </div>
        </section>
        <!-- 注册表单 -->
        <section v-show="showRegisterForm">
          <h3 class="text-lg font-bold mb-6">注册</h3>
          <div class="space-y-4">
            <div class="space-y-2">
              <label class="text-lg font-bold">邮箱</label>
              <input
                  type="text"
                  class="input input-bordered w-full"
                  placeholder="请输入邮箱"
                  v-model="blogRegisterForm.email"/>
            </div>
            <div class="space-y-2">
              <label class="text-lg font-bold">密码</label>
              <input
                  type="password"
                  class="input input-bordered w-full"
                  placeholder="密码不小于5位"
                  v-model="blogRegisterForm.password"/>
            </div>
            <div class="space-y-2">
              <label class="text-lg font-bold">确认密码</label>
              <input
                  type="password"
                  class="input input-bordered w-full"
                  placeholder="请再次输入密码"
                  v-model="blogRegisterForm.ensurePassword"/>
            </div>
            <div class="space-y-2">
              <label class="text-lg font-bold">验证码</label>
              <div class="flex items-center">
                <input
                    type="text"
                    class="input input-bordered w-full"
                    placeholder="请输入验证码"
                    v-model="blogRegisterForm.code"/>
                <button
                    class="btn btn-outline w-28 ml-4"
                    :disabled="btnDisabled"
                    @click="getCode(blogRegisterForm.email,'1')">
                  {{ btnText }}
                </button>
              </div>
            </div>
            <div class="space-y-2">
              <p>
                已有账号？<a class="link link-success no-underline" @click="switchToForm('login')">前往登录</a>
              </p>
              <button class="btn btn-lg btn-primary w-full" @click="handleRegister">
                注册并登录
              </button>
            </div>
          </div>
        </section>
        <!-- 忘记密码表单 -->
        <section v-show="showForgetPwdForm">
          <h3 class="text-lg font-bold mb-6">忘记密码</h3>
          <div class="space-y-4">
            <div class="space-y-2">
              <label class="text-lg font-bold">邮箱</label>
              <input
                  type="text"
                  class="input input-bordered w-full"
                  placeholder="请输入邮箱"
                  v-model="blogForgetForm.email"
              />
            </div>
            <div class="space-y-2">
              <label class="text-lg font-bold">密码</label>
              <input
                  type="password"
                  class="input input-bordered w-full"
                  placeholder="密码不小于5位"
                  v-model="blogForgetForm.password"
              />
            </div>
            <div class="space-y-2">
              <label class="text-lg font-bold">确认密码</label>
              <input
                  type="password"
                  class="input input-bordered w-full"
                  placeholder="请再次输入密码"
                  v-model="blogForgetForm.ensurePassword"
              />
            </div>
            <div class="space-y-2">
              <label class="text-lg font-bold">验证码</label>
              <div class="flex items-center">
                <input
                    type="input"
                    class="input input-bordered w-full"
                    placeholder="请输入验证码"
                    v-model="blogForgetForm.code"
                />
                <button
                    class="btn btn-outline w-28 ml-4"
                    :disabled="btnDisabled"
                    @click="getCode(blogForgetForm.email,'2')">
                  {{ btnText }}
                </button>
              </div>
            </div>
            <div class="space-y-2">
              <p>
                已有账号？<a class="link link-success no-underline" @click="switchToForm('login')">前往登录</a>
              </p>
              <button class="btn btn-lg btn-primary w-full" @click="handleForgetPwd">
                提 交
              </button>
            </div>
          </div>
        </section>
      </AnnModal>
    </section>
  </div>
</template>
<script setup lang="ts">
import {
  getToken,
  getUserInfoFromCookie,
  removeToken,
  removeUserInfo,
  setUserInfoToCookie
} from "~/utils/cookie";
import {ref, reactive, onMounted} from "vue";
import {useThemeStore} from "~/store/theme";
import {useUserStore} from "~/store/user";
import type {BlogLoginForm, BlogRegisterForm, BlogForgetForm, BlogUserWebVO, SendCodeBo,} from "~/api/user/types";
import {sendCode, forgetPwd, socialLogin, logout, queryBlogUserInfo} from "~/api/user";
import {showMessage} from "~/utils/toast";

const themeStore = useThemeStore();
const userStore = useUserStore();
const userInfo = ref<BlogUserWebVO>();
const blogToken = ref(getToken());
const menuTree = reactive<MenuTree[]>([
  {
    name: "首页",
    link: "/",
    icon: "twemoji:house",
  },
  {
    name: "归档",
    link: "/archive",
    icon: "twemoji:card-file-box",
  },
  {
    name: "说说",
    link: "/talk",
    icon: "icon-park:message-one",
  },
  {
    name: "相册",
    link: "/album",
    icon: "flat-color-icons:gallery",
  },
  {
    name: "留言",
    link: "/message",
    icon: "noto-v1:e-mail",
  },
  /*{
    name: "娱乐",
    link: "",
    icon: "twemoji:video-game",
    children: [
      {
        name: "相册",
        link: "/album",
        icon: "flat-color-icons:gallery",
      },
      {
        name: "留言",
        link: "/message",
        icon: "noto-v1:e-mail",
      },
    ],
  },*/
  {
    name: "友情链接",
    link: "/friendLink",
    icon: "twemoji:clinking-glasses",
  },
  {
    name: "关于",
    link: "/about",
    icon: "twemoji:information",
  },
]);
// 表单数据
const blogLoginForm = reactive<BlogLoginForm>({
  email: "",
  password: "",
  code: "",
});
const blogRegisterForm = reactive<BlogRegisterForm>({
  email: "",
  password: "",
  ensurePassword: "",
  code: "",
});
const blogForgetForm = reactive<BlogForgetForm>({
  email: "",
  password: "",
  ensurePassword: "",
  code: "",
});
const codeBo = reactive<SendCodeBo>({
  email: "",
  type: "",
});
// UI 状态
const modalId = ref<string>("loginModal")
const isDetailOpen = ref(false);
let countDownDetailInterval: NodeJS.Timer | null = null;
const showLoginForm = ref(true);
const showRegisterForm = ref(false);
const showForgetPwdForm = ref(false);
const pwdLogin = ref(true);
const checked = ref(false)
const btnDisabled = ref(false);
const btnText = ref("发送验证码");
const countDownSeconds = ref(60);
let countDownInterval: NodeJS.Timer;
const isTop = ref(true);

onMounted(() => {
  document.addEventListener("click", () => {
    checked.value = false;
  });
  window.addEventListener("scroll", handleScroll);
  if (blogToken.value) {
    getInfo()
  }
});
const handleMouseOverDetails = () => {
  if (countDownDetailInterval) {
    clearInterval(countDownDetailInterval);
  }
  isDetailOpen.value = true
};

const handleMouseLeaveDetails = () => {
  if (countDownDetailInterval) {
    clearInterval(countDownDetailInterval);
  }
  countDownDetailInterval = setInterval(() => {
    isDetailOpen.value = false
  }, 300);
};

// 重置表单
const resetLoginForm = () => {
  blogLoginForm.email = "";
  blogLoginForm.password = "";
  blogLoginForm.code = "";
};

const handleScroll = () => {
  isTop.value = window.scrollY === 0;
};

// 获取用户信息
const getInfo = async () => {
  //先从cookie中获取
  userInfo.value = await getUserInfoFromCookie()
  if (!userInfo.value) {
    //获取不到再去调用接口
    const {data: res} = await useAsyncData("queryBlogUserInfo", () => queryBlogUserInfo())
    userInfo.value = res.value as BlogUserWebVO
    await setUserInfoToCookie(userInfo.value)
  }
};

const validateForm = () => {
  const {email, password, code} = blogLoginForm;
  if (pwdLogin.value && (!email || !password)) {
    showMessage("邮箱或密码不能为空", "danger");
    return false;
  }
  if (!pwdLogin.value && (!email || !code)) {
    showMessage("邮箱或验证码不能为空", "danger");
    return false;
  }
  return true;
};
const handleLogin = async () => {
  if (!validateForm()) {
    return;
  }
  const loginType = pwdLogin.value ? "pwdLogin" : "emailCodeLogin";
  const {data: res} = await userStore.doLogin(blogLoginForm, loginType);
  if (res.value?.code == 200) {
    showMessage("登录成功");
    resetLoginForm();
    location.reload()
    await getInfo()
  }
};

const handleForgetPwd = async () => {
  const {data: res} = await useAsyncData("forgetPwd", () =>
      forgetPwd(blogForgetForm)
  );
  if (res.value?.code == 200) {
    showMessage("提交成功");
  }
};
const handleRegister = async () => {
  await userStore.doRegister(blogRegisterForm)
  showMessage("注册并登录成功");
  resetLoginForm();
  location.reload()
  await getInfo()
}

const handleSocialLogin = async (source: string) => {
  const {data: res} = await useAsyncData("socialLogin", () => socialLogin(source));
  window.open(res.value as string, "_self");
};

const handleLogout = async () => {
  await useAsyncData("logout", () => logout());
  removeToken();
  removeUserInfo();
  location.reload();
  showMessage("退出成功");
};

// 发送验证码
const getCode = async (email: string, type: string) => {
  codeBo.email = email
  codeBo.type = type
  const {data: res} = await useAsyncData("sendCode", () => sendCode(codeBo));
  showMessage("发送成功");
  btnDisabled.value = true;
  // 开始倒计时
  startCountDown();
};

// 开始倒计时函数
const startCountDown = () => {
  // 清除之前的定时器
  clearInterval(countDownInterval);

  // 初始化倒计时秒数和按钮文本
  countDownSeconds.value = 60;
  btnText.value = `${countDownSeconds.value}s`;

  // 设置新的定时器
  countDownInterval = setInterval(() => {
    countDownSeconds.value--;

    if (countDownSeconds.value <= 0) {
      // 倒计时结束时清除定时器并恢复按钮状态
      clearInterval(countDownInterval);
      btnDisabled.value = false;
      btnText.value = "获取验证码";
    } else {
      // 更新按钮文本
      btnText.value = `${countDownSeconds.value}s`;
    }
  }, 1000);
};
// 切换表单
const switchToForm = (formType: string) => {
  showLoginForm.value = formType === "login";
  showRegisterForm.value = formType === "register";
  showForgetPwdForm.value = formType === "forgetPwd";
};
</script>
